# Copyright (c) 2009 Vitja Makarov <vitja.makarov@gmail.com>
# Licensed under the terms of the MIT License (see LICENSE.txt)

from django.shortcuts import *
from django.template import RequestContext
from django.conf import settings
from django.contrib.auth.decorators import *
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.core import urlresolvers
from django.utils.translation import ugettext as _

from translate.trans import *
from translate.decorators import force_translation_update
from translate.forms import ModelTranslateForm
from translate.models import Language

class Wrapper:
    def __init__(self, model):
        self.model = model
        self.name = '%s.%s' % (model._meta.app_label, model._meta.object_name)
    def __unicode__(self):
        return self.name
    @property
    def url(self):
        return urlresolvers.reverse('translate.browse_objects',
                        args=(self.model._meta.app_label, self.model._meta.object_name.lower()))
    def get_perm(self, name):
        return '%s.%s_%s' % (self.model._meta.app_label, name, self.model._meta.object_name.lower())

@permission_required('translate.add_simpletranslation')
@force_translation_update
def browse_models(request):
    models = []
    for i in translator.models:
        model = Wrapper(i)
        if request.user.has_perm(model.get_perm('change')):
            models.append(model)
    return render_to_response("translate/browse-models.html",
                                {'models': models},
                                RequestContext(request))

@permission_required('translate.add_simpletranslation')
@force_translation_update
def browse_objects(request, app_label, obj_name):
    try:
        model = translator.models_by_name['/'.join((app_label, obj_name))]
    except KeyError:
        raise Http404, _("No model found")
    wrapped = Wrapper(model)
    if not request.user.has_perm(wrapped.get_perm('change')):
        raise Http404

    paginator = Paginator(model._default_manager.all(), 50)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        objects = paginator.page(page)
    except (EmptyPage, InvalidPage):
        objects = paginator.page(paginator.num_pages)
    return render_to_response("translate/browse-objects.html",
                                {'model': wrapped,
                                 'objects': objects, },
                                RequestContext(request))

@permission_required('translate.add_simpletranslation')
@force_translation_update
def translate_obj(request, app_label, obj_name, pk):
    try:
        model = translator.models_by_name['/'.join((app_label, obj_name))]
    except KeyError:
        raise Http404, _("No model found")
    wrapped = Wrapper(model)
    if not request.user.has_perm(wrapped.get_perm('change')):
        raise Http404

    obj = get_object_or_404(model, pk=pk)
    lang = request.GET.get('lang', None)

    if request.method == 'POST':
        form = ModelTranslateForm(obj, request.POST, lang=lang)
        if form.is_valid():
            if form.has_changed():
                form.save()
            if hasattr(obj, 'get_absolute_url'):
                return HttpResponseRedirect(obj.get_absolute_url())
            else:
                return HttpResponseRedirect(wrapped.url)
    else:
        form = ModelTranslateForm(obj, lang=lang)
    language = translator.get_language(form.lang)
    return render_to_response("translate/translate-obj.html",
                                {'obj': obj, 'form': form, 'language': language, 'languages': Language.objects.all()},
                                RequestContext(request))
